package com.zyl.Ecs.common.exception;

import com.zyl.Ecs.common.response.Result;
import com.zyl.Ecs.common.utils.CUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.List;

/**
 * @version v1.0
 * @ProjectName: Ecs
 * @Package: com.zyl.Ecs.common.exception
 * @ClassName: GlobalExceptionHandler
 * @Description TODO (全局异常处理类)
 * @Author 翟玉龙
 * @Date 2024/12/4-11:32
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /*
     *  处理异常, 当Service层出现异常时
     *  会被该方法捕获，执行对应的处理策略
     */
    @ExceptionHandler(EcsException.class)
    public Result<?> EcsExceptionHandler(EcsException e){
        log.info("发生异常：{}", e.getMessage());
        return Result.error(e.getCode(), e.getMessage());
    }

    /*
     * 参数校验异常处理
     * @param e 异常类
     * @return 异常提示
     */
    @ExceptionHandler(BindException.class)
    public Result<?> handleException(BindException e) {

        BindingResult bindingResult = e.getBindingResult();

        List<String> errors = new ArrayList<>();

        bindingResult.getFieldErrors().forEach(error -> {
            String objectName = error.getObjectName();
            String fieldName = error.getField();
            String errorMessage = error.getDefaultMessage();
            errors.add(objectName + "." + fieldName + ": " + errorMessage);
        });

        StringBuilder error = new StringBuilder();
        for (int i = 0; i < errors.size(); i++) {
            error.append(errors.get(i));
            if (i < errors.size() - 1) {
                error.append(",");
            }
        }

        CUtil.logError("发生异常：" + error);
        return Result.error(error.toString());
    }

    /*
     *  处理异常, 当Controller层出现异常时
     *  会被该方法捕获，执行对应的处理策略
     */
    @ExceptionHandler({Exception.class})
    public Result<?> exceptionHandler(Exception e){
        // 将Validated异常信息的有用部分提取出来并返回
        log.error("出现异常：{}", e.toString());
        return Result.error(500,
                String.format("服务器异常: %s", e.getMessage()));
    }

}

